import { Popover, message } from 'antd';
import React, { useState, useEffect } from 'react';
import Speaking from '@/components/Speaking';
import wx from 'weixin-js-sdk';
import { getFetch } from '@/utils/doFetch';
import { useAsyncEffect, useInterval } from 'ahooks';
import { formFetch } from '../../utils/doFetch';

function Recorder({ socket, companies }) {
  useAsyncEffect(async () => {
    let res = await getFetch({
      url: '/wbn-api/wechat/signature',
      params: { url: document.URL },
    });

    if (res.code == 0) {
      wx.config({
        debug: false,
        appId: res.data.app_id,
        timestamp: res.data.timestamp,
        nonceStr: res.data.nonce_str,
        signature: res.data.signature,
        jsApiList: ['chooseImage', 'getLocalImgData'], // 需要使用的API列表
      });
      wx.error(function () {});
    }
  }, []);

  function base64ToFile(base64, fileName) {
    // base64转file文件
    let arr = base64.split(',');
    let mime = arr[0].match(/:(.*?);/)[1];
    let bytes = atob(arr[1]);
    let n = bytes.length;
    let ia = new Uint8Array(n);
    while (n--) {
      ia[n] = bytes.charCodeAt(n);
    }
    return new File([ia], fileName, { type: mime });
  }

  async function Uploadfile(file) {
    const params = new FormData();
    params.append('file', file);
    let res = await formFetch({ url: '/wbn-api/file', params: params });
    if (res?.data?.origin_url) {
      socket.emit(
        'customer-message',
        JSON.stringify({
          company_id: companies?.id,
          message_type: 'picture',
          message_content: res?.data?.origin_url,
        }),
      );
    } else {
      alert(JSON.stringify(res));
      message.error('上传失败');
    }
  }

  return (
    <div
      style={{ padding: 12, borderRadius: 8, backgroundColor: '#fff' }}
      onClick={(e) => {
        e.preventDefault();
        wx.chooseImage({
          count: 1, // 默认9
          sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
          sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
          success: function (res) {
            let file = res.localIds[0];
            wx.getLocalImgData({
              // 使用这个方法将chooseImage返回的临时路径转换为base64编码
              localId: file.toString(),
              success: function (res) {
                const localData = res.localData;
                let imageBase64 = '';
                if (localData.indexOf('data:image') == 0) {
                  //苹果的直接赋值，默认生成'data:image/jpeg;base64,'的头部拼接
                  imageBase64 = localData;
                } else {
                  //此处是安卓中的唯一得坑！在拼接前需要对localData进行换行符的全局替换
                  //此时一个正常的base64图片路径就完美生成赋值到img的src中了
                  imageBase64 =
                    'data:image/jpeg;base64,' + localData.replace(/\n/g, '');
                }
                let file = base64ToFile(imageBase64, 'headImage.jpg'); // 在将base64编码转换成file文件即可上传

                Uploadfile(file);
              },
            });
          },
        });
      }}
    >
      <div
        style={{
          width: 36,
          height: 36,
          userSelect: 'none',
          background: `url(${require('@/assets/image.svg')}) no-repeat center`,
          backgroundSize: 'contain',
        }}
      ></div>
    </div>
  );
}

export default Recorder;
